package cn.wildfire.chat.app.extendsion.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;

import java.security.InvalidParameterException;

import androidx.annotation.NonNull;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;

/**
 * Create by HEKE, 2019/10/15 10:03
 * TODO 自定义对应APP风格提示窗口
 */
public class CustomAppUIDialog extends Dialog implements DialogInterface.OnDismissListener {

    // 确认取消
    public static final int TYPE_CONFIRM_CANCLE = 0x00;
    // 单按钮
    public static final int TYPE_SINGLE_BUTTON = 0x01;

    @BindView(R2.id.tv_message_title)
    TextView tvMessageTitle;
    @BindView(R2.id.tv_reminder)
    TextView tvReminder;
    @BindView(R2.id.btn_cancel)
    Button btnCancel;
    @BindView(R2.id.btn_confirm)
    Button btnConfirm;
    @BindView(R2.id.cancleLayout)
    LinearLayout cancleLayout;
    @BindView(R2.id.confirmLayout)
    LinearLayout confirmLayout;
    @BindView(R2.id.appuiDialogRootLayout)
    LinearLayout appuiDialogRootLayout;
    @BindView(R2.id.closeTxt)
    TextView closeTxt;

    private OnAppUIDialogCheckedListener onAppUIDialogCheckedListener;
    private String title;
    private String message;
    private String[] buttonTitles;
    private int type;

    public CustomAppUIDialog(@NonNull Context context, String title, String message, String[] buttonTitles,
                             int type, OnAppUIDialogCheckedListener onAppUIDialogCheckedListener) {
        super(context, R.style.transparentDiag);
        this.title = title;
        this.message = message;
        this.buttonTitles = buttonTitles;
        this.type = type;
        this.onAppUIDialogCheckedListener = onAppUIDialogCheckedListener;
        if (type == TYPE_CONFIRM_CANCLE) {
            if (buttonTitles == null || buttonTitles.length != 2) {
                throw new InvalidParameterException("Type with titles invalid !");
            }
        } else {
            if (buttonTitles == null || buttonTitles.length == 0) {
                throw new InvalidParameterException("ButtonTitles invalid !");
            }
        }
    }

    private void init() {
        tvMessageTitle.setText(TextUtils.isTextEmpty(title) ? "" : title);
        tvMessageTitle.setVisibility(TextUtils.isTextEmpty(title) ? View.GONE : View.VISIBLE);
        tvReminder.setText(TextUtils.isTextEmpty(message) ? "" : message);
        cancleLayout.setVisibility((type == TYPE_CONFIRM_CANCLE) ? View.VISIBLE : View.GONE);
        if (buttonTitles != null && buttonTitles.length > 0) {
            btnConfirm.setText(TextUtils.isTextEmpty(buttonTitles[0]) ? "" : buttonTitles[0]);
            if (type == TYPE_CONFIRM_CANCLE) {
                btnCancel.setText(TextUtils.isTextEmpty(buttonTitles[1]) ? "" : buttonTitles[1]);
            }
        }
        closeTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
                if (onAppUIDialogCheckedListener != null) {
                    onAppUIDialogCheckedListener.behavior(false, true);
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_custom_view);
        ButterKnife.bind(this);
        setOnDismissListener(this);
        init();
    }

    // 标记是否点击控件
    protected boolean clickedView;

    @OnClick({R2.id.btn_cancel, R2.id.btn_confirm})
    public void onViewClicked(View view) {
        clickedView = true;
        int id = view.getId();
        if (id == R.id.btn_cancel) {
            dismiss();
            if (onAppUIDialogCheckedListener != null) {
                onAppUIDialogCheckedListener.behavior(false, false);
            }
        } else if (id == R.id.btn_confirm) {
            dismiss();
            if (onAppUIDialogCheckedListener != null) {
                onAppUIDialogCheckedListener.behavior(true, false);
            }
        }
    }

    /**
     * 设置标题内容显示方式
     */
    public void showLeftTitleMessageCenterStyle() {
        if (tvMessageTitle == null) {
            return;
        }
        int margin = getContext().getResources().getDimensionPixelSize(R.dimen.y40);
        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        rl.setMargins(margin, margin, 0, 0);
        rl.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        tvMessageTitle.setLayoutParams(rl);
        RelativeLayout.LayoutParams rl2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        rl2.setMargins(2 * margin, margin, margin, margin);
        rl2.addRule(RelativeLayout.BELOW, tvMessageTitle.getId());
        rl2.addRule(RelativeLayout.ALIGN_PARENT_LEFT | RelativeLayout.CENTER_VERTICAL);
        tvReminder.setLayoutParams(rl2);
    }

    /**
     * 设置标题显示方式
     */
    public void showLeftTitle() {
        if (tvMessageTitle == null) {
            return;
        }
        int margin = getContext().getResources().getDimensionPixelSize(R.dimen.y40);
        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        rl.setMargins(margin, margin, 0, 0);
        rl.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        tvMessageTitle.setLayoutParams(rl);
    }

    /**
     * 设置标题消息居中显示方式
     */
    public void showTextAllCenter() {
        if (tvMessageTitle == null) {
            return;
        }
        int margin = getContext().getResources().getDimensionPixelSize(R.dimen.y40);
        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        rl.setMargins(0, margin, 0, 0);
        rl.addRule(RelativeLayout.CENTER_HORIZONTAL);
        tvMessageTitle.setLayoutParams(rl);
        RelativeLayout.LayoutParams rl2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        rl2.setMargins(margin, margin, margin, margin);
        rl2.addRule(RelativeLayout.BELOW, tvMessageTitle.getId());
        rl2.addRule(RelativeLayout.CENTER_HORIZONTAL);
        tvReminder.setLayoutParams(rl2);
    }

    protected boolean isCorverShowing;

    /**
     * 显示透明背景底色
     */
    public void showCover() {
        try {
            isCorverShowing = true;
            Window window = getWindow();
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.width = getContext().getResources().getDisplayMetrics().widthPixels;
            layoutParams.height = getContext().getResources().getDisplayMetrics().heightPixels;
            layoutParams.gravity = Gravity.CENTER;
            layoutParams.x = 0;
            layoutParams.y = 0;
            window.setAttributes(layoutParams);
            window.setBackgroundDrawable(new ColorDrawable(0x35000000));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.setStatusBarColor(0x35000000);
                window.setNavigationBarColor(0x35000000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示关闭按钮
     */
    public void showCloseButton() {
        if (closeTxt != null) {
            closeTxt.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置底部确认按钮的显示风格
     *
     * @param style 显示按下弹起时显示的样式内容文件
     * @param ffp   是否填充满父控件
     */
    public void setConfirmStyle(int style, boolean ffp) {
        if (btnConfirm != null) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) btnConfirm.getLayoutParams();
            if (ffp) {
                layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
                layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
            }
            btnConfirm.setLayoutParams(layoutParams);
            if (style != -1) {
                btnConfirm.setBackgroundResource(style);
            }
            if (ffp) {
                setBottonLayoutNoLRMargin(0, 0, 0, 0);
            }
        }
    }

    /**
     * 设置底部取消按钮的显示风格
     *
     * @param style 显示按下弹起时显示的样式内容文件
     * @param ffp   是否填充满父控件
     */
    public void setCancleStyle(int style, boolean ffp) {
        if (btnCancel != null) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) btnCancel.getLayoutParams();
            if (ffp) {
                layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
                layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
            }
            btnCancel.setLayoutParams(layoutParams);
            if (style != -1) {
                btnCancel.setBackgroundResource(style);
            }
        }
    }

    /**
     * 设置父控件无左右边距
     *
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    public void setBottonLayoutNoLRMargin(int left, int top, int right, int bottom) {
        try {
            ViewParent viewParent = confirmLayout.getParent();
            if (viewParent != null) {
                LinearLayout linearLayout = (LinearLayout) viewParent;
                ViewGroup.LayoutParams layoutParams = linearLayout.getLayoutParams();
                if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
                    ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams;
                    marginLayoutParams.setMargins(left, top, right, bottom);
                }
                linearLayout.setLayoutParams(layoutParams);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置确认按钮的字体显示颜色
     *
     * @param color
     */
    public void setConfirmTextColor(int color) {
        if (btnConfirm != null) {
            btnConfirm.setTextColor(getContext().getResources().getColor(color));
        }
    }

    /**
     * 设置取消按钮的字体显示颜色
     *
     * @param color
     */
    public void setCancleTextColor(int color) {
        if (btnCancel != null) {
            btnCancel.setTextColor(getContext().getResources().getColor(color));
        }
    }

    /**
     * 获取标题控件
     */
    public TextView getTitleView() {
        return tvMessageTitle;
    }

    /**
     * 获取显示内容控件
     */
    public TextView getMessageView() {
        return tvReminder;
    }

    /**
     * 获取取消按钮
     */
    public Button getCancelButton() {
        return btnCancel;
    }

    /**
     * 获取确定按钮
     */
    public Button getBtnConfirmButton() {
        return btnConfirm;
    }

    /**
     * 获取右上角关闭控件
     */
    public TextView getCloseView() {
        return closeTxt;
    }

    @Override
    public void onDismiss(DialogInterface dialogInterface) {
        if (!clickedView) {
            if (onAppUIDialogCheckedListener != null) {
                onAppUIDialogCheckedListener.behavior(false, true);
            }
        }
    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event) {
        if (isCorverShowing) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    try {
                        int x = (int) event.getX();
                        int y = (int) event.getY();
                        int left = appuiDialogRootLayout.getLeft();
                        int top = appuiDialogRootLayout.getTop();
                        int width = appuiDialogRootLayout.getMeasuredWidth();
                        int height = appuiDialogRootLayout.getMeasuredHeight();
                        if (!(x >= left && x <= left + width && y >= top && y <= top + height)) {
                            dismiss();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
        return super.onTouchEvent(event);
    }

    /**
     * 窗口内容操作选择回调接口
     */
    public interface OnAppUIDialogCheckedListener {
        void behavior(boolean confirm, boolean outtouch);
    }

}
